package cn.zane.chatgpt.data.application.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.strategy.SaStrategy;
import cn.dev33.satoken.util.SaFoxUtil;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author: zane
 * @date: 2025-09-18
 * @description: SaToken过滤器配置类 "/user/doLogin", "/weixin/portal/validate", "/error"
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Value("${wx.config.appid}")
    private String appid;
    @Value("${app.config.api-version}")
    private String apiVersion;

    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String wxValidateUrl = "/api/" + apiVersion + "/wx/portal/" + appid;

        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
                .addPathPatterns("/**")
                .excludePathPatterns("/user/doLogin", wxValidateUrl, "/error");
    }

    /**
     * token：随机60位长度字符串
     */
    @PostConstruct
    public void rewriteSaStrategy() {
        // 重写 Token 生成策略
        SaStrategy.instance.createToken = (loginId, loginType) -> SaFoxUtil.getRandomString(60);
    }


}



